package com.baizhi.service.impl;

import com.baizhi.dto.request.StudentDTO;
import com.baizhi.entity.Backlog;
import com.baizhi.entity.Student;
import com.baizhi.entity.User;
import com.baizhi.exception.CodeEnum;
import com.baizhi.mapper.BacklogMapper;
import com.baizhi.mapper.GradeMapper;
import com.baizhi.mapper.StudentMapper;
import com.baizhi.mapper.UserMapper;
import com.baizhi.service.StudentService;
import com.baizhi.service.UserService;
import com.baizhi.utils.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
* @author 16357
* @description 针对表【t_student】的数据库操作Service实现
* @createDate 2024-08-01 14:53:19
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
    implements StudentService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private BacklogMapper backlogMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public Boolean logOutStudent(Integer userId) {
        // 通过userID获取stuId
        //获取学生ID
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).select("pk_sid");
        Integer stuId = studentMapper.selectOne(wrapper).getPkSid();

        //删除student_course表中的信息
        Integer rowA = studentMapper.deleteMyCourseByStuId(stuId);
        //删除t_backlog表中的信息  根据userID删除备忘信息
        QueryWrapper<Backlog> backlogWrapper = new QueryWrapper<>();
        backlogWrapper.eq("user_id",userId);
        int rowB = backlogMapper.delete(backlogWrapper);

        //删除t_student表中的信息 //根据stuId直接删除
        int rowC = studentMapper.deleteById(stuId);

        //删除t_user表中的信息
        int rowD = userMapper.deleteById(userId);

        return true;
    }

    @Override
    @Transactional
    public Boolean registStudent(StudentDTO studentDTO) {
        //1. 拆分studentDTO 为两个对象， User和Student
        User user = buildUserForStudentDTO(studentDTO);
        Student student = buildStudentForStudentDTO(studentDTO);
        //2. 检测用户名是否被占用，如果被占用抛出用户名被占用异常
        User result = userService.getUserByUserName(user.getUserName());
        if(result != null){
            //throw new EnumException(CodeEnum.username_already_exist); // 用户名被占用
            CodeEnum.username_already_exist.throwException();
        }



        //3. 生成盐值，密码加密
        String salt = UUID.randomUUID().toString().toUpperCase(Locale.ROOT);
        String md5Password = MD5Util.getMd5Password(user.getPassword(), salt);

        user.setSalt(salt);
        user.setPassword(md5Password);

        //4. 往t_user表中插入数据  User  添加失败，注册失败异常
        int userRow = userMapper.insert(user);
        //5. 获取user中的id,将id提那家给student
        student.setUserId(user.getPkUid());
        //6. 往t_student表中插入数据 Student  添加失败，抛出注册失败异常
        int stuRow = studentMapper.insert(student);

        if(userRow==0 || stuRow == 0){
            //throw new EnumException(CodeEnum.user_register_fail);
            CodeEnum.user_register_fail.throwException();
        }

        return true;
    }







    /**
     * 将接收的参数StudentDTO中User部分的数据封装成一个User对象
     * @param studentDTO
     * @return
     */
    private User buildUserForStudentDTO(StudentDTO studentDTO){
        User user = new User();
        user.setUserName(studentDTO.getUserName());
        user.setPassword(studentDTO.getPassword());
        user.setRealName(studentDTO.getName());
        user.setPhone(studentDTO.getPhone());
        user.setSex(studentDTO.getSex());

        user.setAddress(studentDTO.getAddress());
        user.setRoleId(3); //学生角色是3
        //补充 修改时间和创建时间的字段
        user.setGmtCreate(new Date());
        user.setGmtModified(new Date());
        return user;
    }

    /**
     * 将接收的参数StudentDTO中Student部分的数据封装成一个Student对象
     * @param studentDTO
     * @return
     */
    private Student buildStudentForStudentDTO(StudentDTO studentDTO){
        Student student = new Student();
        student.setName(studentDTO.getName());
        student.setSex(studentDTO.getSex());
        student.setAddress(studentDTO.getAddress());
        student.setEnrollmentYear(studentDTO.getEnrollYear());
        student.setPhone(studentDTO.getPhone());
        student.setEmergencyContact(studentDTO.getEmergencyContact());
        student.setEmergencyPhone(studentDTO.getEmergencyContactPhone());
        student.setGmtCreate(new Date());
        student.setGmtModified(new Date());

        //班级，
        if(studentDTO.getGradeId()!=null || studentDTO.getGradeId()!=""){
            student.setGradeId(Integer.valueOf(studentDTO.getGradeId()));
        }



        //user_id 也需要插入，那么就需要添加User的时候返回id，不在这里处理
        return student;
    }
}




